<script>
import ZPMixin from "@/uni_modules/z-paging/components/z-paging/js/z-paging-mixin";
import slFilter from "../components/sl-filter/sl-filter.vue";
import { getGoodsList } from "@/api/mall.js";
import navBar from "@/components/layout/navbar/index.vue";
import { mapState, mapMutations } from "vuex";

export default {
  name: "list",
  mixins: [ZPMixin],
  components: {
    navBar,
    slFilter,
  },
  data() {
    return {
      // 活动列表
      activities: [],

      // 当前选中的类别
      currentCategoryIndex: 0,

      // 活动分类，改为list1
      list1: [
        { name: "全部" },
        { name: "品牌活动" },
        { name: "海岛活动" },
        { name: "社群活动" },
        // { name: '自然探索' },
        // { name: '其他活动' }
      ],

      // 筛选相关数据
      filterList: [
        // {
        //   'title': '活动价格',
        //   'key': 'PriceRange',
        //   'isDrow': true,
        //   'isSort': true,
        //   'reflexTitle': true,
        //   'detailList': [
        //     {
        //       'title': '不限价格',
        //       'value': 0
        //     },
        //     {
        //       'title': '0-100元',
        //       'value': '0,100'
        //     },
        //     {
        //       'title': '100-200元',
        //       'value': '100,200'
        //     },
        //     {
        //       'title': '200-300元',
        //       'value': '200,300'
        //     },
        //     {
        //       'title': '300元以上',
        //       'value': '300,99999'
        //     }
        //   ]
        // },
        {
          title: "活动时间",
          key: "TimeRange",
          isDrow: true,
          isSort: true,
          reflexTitle: true,
          detailList: [
            {
              title: "不限时间",
              value: 0,
            },
            {
              title: "本周内",
              value: "thisWeek",
            },
            {
              title: "本月内",
              value: "thisMonth",
            },
            {
              title: "三个月内",
              value: "threeMonths",
            },
          ],
        },
        // {
        //   'title': '排序',
        //   'key': 'SortBy',
        //   'isDrow': false,
        //   'isSort': true,
        //   'sort': 'desc',
        //   'reflexTitle': true,
        //   'detailList': []
        // }
      ],
      themeColor: "#00b7ff",
      titleColor: "#666666",
      IsDesc: {},
      searchParams: {
        
      },
    };
  },
  onLoad() {
    // 初始化页面
    // if(this.selectedLocation.value === 0){
    //   this.$refs.navBarRef && this.$refs.navBarRef.showCustomAction();
    // }
  },
  computed: {
    ...mapState({
      locationList: (state) => state.base.locationList,
      selectedLocation: (state) => state.base.selectedLocation,
    }),
    safeAreaTop() {
      return this.$store.state.app.wxMenuClient.top;
    },
    showCancle() {
      return this.selectedLocation.value !== 0;
    },
  },
  methods: {
    ...mapMutations(["setSelectedLocation"]),
    selectALocation() {
      uni.showActionSheet({
        itemList: this.locationList.map((item) => item.title),
        success: (res) => {
          const selectedLocation = this.locationList[res.tapIndex];
          this.setSelectedLocation(selectedLocation);
          this.$refs.paging.reload();
        },
      });
    },
    // 选择活动分类
    click(item) {
      // 找到点击的索引
      const index = this.list1.findIndex((i) => i.name === item.name);
      this.currentCategoryIndex = index;
      // 重新加载活动列表
      this.$refs.paging.reload();
      console.log("item", item);
    },

    // 处理筛选结果
    handleResult(result) {
      this.IsDesc = result;
      console.log("筛选结果:", result);

      // 清除之前的筛选参数
      Object.keys(this.searchParams).forEach((key) => {
        if (["PriceRange", "TimeRange", "SortBy"].includes(key)) {
          delete this.searchParams[key];
        }
      });

      // 设置新的筛选参数
      if (Object.keys(result).length > 0) {
        const [key, value] = Object.entries(result)[0];
        if (value !== 0 && value !== "") {
          // 不处理"不限"选项
          this.searchParams[key] = value;
        }

        // 重新加载数据
        this.$refs.paging.reload();
      }
    },

    // 加载活动列表 - 使用getGoodsList API
    async queryList(pageNo, pageSize) {
      console.log("查询参数:", this.searchParams);

      try {
        // 从store获取选中的位置
        const selectedLocation = this.$store.state.base.selectedLocation;

        // 构建API请求参数
        const requestParams = {
          // BusinessId: 37, // 指定BusinessId为37
          TypeId: 18,
          Index: pageNo,
          Size: pageSize,
          BusinessAreaId: selectedLocation.value,
          FiledOrder: "Sort desc",
        };

        // 添加分类条件
        if (this.currentCategoryIndex !== 0) {
          requestParams.ProductCategoryId = this.currentCategoryIndex;
        }

        // 添加价格筛选
        if (this.searchParams.PriceRange) {
          const [min, max] =
            this.searchParams.PriceRange.split(",").map(Number);
          requestParams.MinPrice = min;
          requestParams.MaxPrice = max;
        }

        // 添加时间筛选
        if (this.searchParams.TimeRange) {
          const now = new Date();
          let startDate = null;

          if (this.searchParams.TimeRange === "thisWeek") {
            // 计算本周开始日期
            const day = now.getDay() || 7;
            startDate = new Date(
              now.getTime() - (day - 1) * 24 * 60 * 60 * 1000
            );
          } else if (this.searchParams.TimeRange === "thisMonth") {
            // 计算本月开始日期
            startDate = new Date(now.getFullYear(), now.getMonth(), 1);
          } else if (this.searchParams.TimeRange === "threeMonths") {
            // 计算三个月前的日期
            startDate = new Date(now.getFullYear(), now.getMonth() - 3, 1);
          }

          if (startDate) {
            requestParams.StartDate = startDate.toISOString().split("T")[0];
            requestParams.EndDate = new Date().toISOString().split("T")[0];
          }
        }

        // 添加排序条件
        if (this.searchParams.SortBy) {
          requestParams.OrderField = "Price"; // 按价格排序
          requestParams.OrderType = this.searchParams.SortBy === "desc" ? 1 : 0; // 1降序，0升序
        }

        // 调用API获取数据
        const response = await getGoodsList(requestParams);

        if (response && response.Data) {
          // 格式化数据以匹配现有模板
          const formattedData = response.Data.map((item) => ({
            id: item.Id,
            title: item.Name,
            subtitle: item.ShortName || "活动",
            image: item.Img,
            startDate: this.formatDate(item.ProductSpecList[0]?.StartDate),
            endDate: this.formatDate(item.ProductSpecList[0]?.EndDate),
            location: item.Address || "万山群岛",
            price: item.Price,
          }));

          // 完成加载，更新数据
          this.$refs.paging.complete(formattedData);
        } else {
          // 加载失败
          this.$refs.paging.complete([]);
        }
      } catch (error) {
        console.error("获取活动列表失败:", error);
        this.$refs.paging.complete(false);
        uni.showToast({
          title: "加载数据失败",
          icon: "none",
        });
      }
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return "";

      const formattedEndDate = dateStr.replace(/-/g, "/");
      const date = new Date(formattedEndDate);
      if (isNaN(date.getTime())) return "";

      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");

      return `${year}.${month}.${day}`;
    },

    // 选择活动
    selectActivity(activity) {
      uni.navigateTo({
        url: `/mall_subpages/goods/index?id=${activity.id}&type=8`,
      });
    },

    locationChanged() {
      this.$refs.paging.reload();
    },

    // 计算活动时间是否过期
    calcuActiveDate(endDate) {
      if (!endDate) return false;
      const formattedEndDate = endDate.replace(/\./g, "/");
      const activityEndDate = new Date(formattedEndDate);
      const currentDate = new Date();
      return activityEndDate < currentDate;
    },
  },
};
</script>

<template>
  <view class="list-container">
    <z-paging
      ref="paging"
      v-model="activities"
      @query="queryList"
      refresher-enabled
    >
      <!-- 顶部固定内容 -->
      <template #top>
        <!-- 顶部导航栏 -->
        <view class="header">
          <nav-bar
            ref="navBarRef"
            title="活动列表"
            bg-color="transparent"
            :noCustomNavbar="false"
          />
          <!-- 活动分类 -->
          <!--          <view class="tabs-container">-->
          <!--            <u-tabs :list="list1" @click="click"></u-tabs>-->
          <!--          </view>-->
          <!-- 添加筛选器 -->
          <view class="header-act">
            <view class="location" @click.stop="selectALocation">
              <uni-icons
                type="location"
                size="20"
                style="margin-right: 10rpx"
              />
              <view class="location-title">{{ selectedLocation.title }}</view>
              <view class="location-arrow"></view>
            </view>
            <!-- <sl-filter
              :independence="true"
              :topFixed="false"
              :navHeight="44"
              :color="titleColor"
              :isDesc="IsDesc"
              :themeColor="themeColor"
              :menuList.sync="filterList"
              class="header-filter"
              @result="handleResult"
            /> -->
          </view>
        </view>
      </template>

      <!-- 活动列表 -->
      <view class="activity-list">
        <view
          v-for="activity in activities"
          :key="activity.id"
          class="activity-card"
          @click="selectActivity(activity)"
        >
          <!-- 活动图片 -->
          <view class="activity-banner">
            <view v-if="calcuActiveDate(activity.endDate)" class="logo">
              <image
                src="https://wzws.wanshanlundiao.cn/upload/img/ws_static/static/huodong/expire_status.png"
                mode="widthFix"
                class="logo-img"
              />
            </view>
            <view class="bg">
              <image :src="activity.image" mode="aspectFill" class="bg-img" />
            </view>
          </view>

          <!-- 活动信息 -->
          <view class="activity-info">
            <view class="activity-header">
              <view class="activity-title-wrapper">
                <text class="activity-subtitle">{{ activity.subtitle }}:</text>
                <text class="activity-title">「{{ activity.title }}」</text>
              </view>
            </view>

            <view class="activity-details">
              <view class="detail-item">
                <text class="detail-label">时间:</text>
                <text class="detail-value"
                  >{{ activity.startDate }}-{{ activity.endDate }}</text
                >
              </view>
              <view class="detail-item">
                <text class="detail-label">地点:</text>
                <text class="detail-value">{{ activity.location }}</text>
                <view class="view-details-btn">查看详情</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>
  </view>
</template>

<style scoped lang="scss">
.list-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 顶部导航栏 */
.header {
  background: url("https://wzws.wanshanlundiao.cn:443/upload/img/20250408/202504081748261598.png")
    no-repeat;
  background-size: cover;
  &-act {
    display: flex;
    align-items: center;
    background: #fff;
    padding: 0 30rpx 0 30rpx;
    // margin: 0 0 20rpx 0;
    height: 100rpx;
    .location {
      display: flex;
      align-items: center;
      border-radius: 100px;
      border: 1px solid #dadbde;
      padding: 6rpx 14rpx;
      opacity: 0.8;
      &-title {
        font-size: $uni-font-size-base;
      }
      &-arrow {
        width: 0;
        height: 0;
        border-style: solid;
        border-width: 10rpx 6rpx 0 6rpx;
        border-color: #333 transparent transparent transparent;
        margin-left: 10rpx;
      }
    }
  }
  &-filter {
    flex: 1;
    margin-left: 16rpx;
  }
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  height: 60rpx;

  .back-btn {
    width: 30rpx;

    image {
      transform: rotate(180deg);
      width: 13rpx;
      height: 24rpx;
    }
  }

  .page-title {
    flex: 1;
    text-align: center;
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }

  .right-icons {
    display: flex;

    .icon-more,
    .icon-target {
      margin-left: 30rpx;
      color: #333;
    }
  }
}

/* 活动分类标签容器 */
.tabs-container {
  margin-bottom: 10rpx;
}

/* 新的活动列表样式 */
.activity-list {
  padding: 30rpx;
}

.activity-card {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 40rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .activity-banner {
    width: 100%;
    height: 300rpx;
    position: relative;
    .logo {
      position: absolute;
      top: 10rpx;
      right: 10rpx;
      width: 120rpx;
      height: 120rpx;
      &-img {
        width: 100%;
      }
    }
    .bg {
      width: 100%;
      height: 100%;
      &-img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }

  .activity-info {
    padding: 20rpx;

    .activity-header {
      margin-bottom: 10rpx;

      .activity-title-wrapper {
        margin-bottom: 5rpx;

        .activity-subtitle {
          font-size: 26rpx;
          color: #666;
          margin-right: 8rpx;
        }

        .activity-title {
          font-size: 30rpx;
          font-weight: bold;
          color: #333;
        }
      }
    }

    .activity-details {
      margin-bottom: 0;

      .detail-item {
        display: flex;
        align-items: center;
        margin-bottom: 5rpx;
        font-size: 24rpx;
        color: #666;

        .detail-label {
          margin-right: 8rpx;
          color: #999;
        }

        .detail-value {
          flex: 1;
        }

        .view-details-btn {
          flex-shrink: 0;
          display: inline-block;
          padding: 4rpx 16rpx;
          font-size: 22rpx;
          color: #56c4d8;
          border: 1px solid #56c4d8;
          border-radius: 20rpx;
        }
      }
    }
  }
}
</style>